package com.xyw.code.taobaokeapi.rest;

import com.xyw.code.taobaokeapi.service.WeChatService;
import com.xyw.code.taobaokeapi.util.WeChatUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/8/7
 * Time: 上午8:42
 * Email: 1328312923@qq.com
 * Description: No Description
 **/
@Api(value="微信api")
@RestController
@RequestMapping("/wx")
public class WeChatController {

    @Autowired
    private WeChatService weChatService;
    @GetMapping("/test")
    public String test(){
        return "aaaa";
    }

    @GetMapping("/wechat")
    public void login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if (WeChatUtil.checkSignature(signature, timestamp, nonce)) {
                out.write(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }
    /**
     * 此处是处理微信服务器的消息转发的
     */
    @PostMapping(value = "wechat")
    public String processMsg(HttpServletRequest request) {
        // 调用核心服务类接收处理请求
        return weChatService.processRequest(request);
    }
}
